package com.example.mmkvdemo

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.router.RouterCenter
import com.example.lib_common.utils.MMKVUtils
import com.example.lib_common.utils.ToolUtils

class MainActivity : AppCompatActivity() {
    private val TAG = "mmkvLog"
    private val REQUEST_PERMISSION_CODE = 100
    private var PERMISSIONS: Array<String> = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE
    )
    private val textView:TextView by lazy { findViewById(R.id.tv_test) }
    private val tvBackData:TextView by lazy { findViewById(R.id.tv_back_data) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ARouter.getInstance().inject(this)
        // 检查并请求权限
        if (checkPermissions()) {
            // 已经有权限，执行文件读写操作
            performFileOperations()
        } else {
            // 请求权限
            requestPermission()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        textView.setOnClickListener {
            // 读取数据
            val value1: String = MMKVUtils.getInstance().decodeString("key1")
            val age: Int = MMKVUtils.getInstance().decodeInt("age")
            val sex: String = MMKVUtils.getInstance().decodeString("sex")
            val address: String = MMKVUtils.getInstance().decodeString("address")
            val birthday: String = MMKVUtils.getInstance().decodeString("birthday")
            val account: String = MMKVUtils.getInstance().decodeString("account")
            val identity: Boolean = MMKVUtils.getInstance().decodeBoolean("identity")
            val amount: Double = MMKVUtils.getInstance().decodeDouble("amount")
            Log.d(TAG, "====数据为===$value1$age$sex$address$birthday$account$identity$account$amount")
            if(!TextUtils.isEmpty(value1)){
                textView.text = value1
            }else{
                textView.text = "mmkv工具类测试"
            }

            try {
               // ARouter.getInstance().build("/test/MainActivity").navigation()
               //  ToolUtils.openApp(this@MainActivity,"com.aiuwheufhbiw.webfkwbfe.dy")
                ToolUtils.openApp("com.example.testmmkv", this@MainActivity)
            }catch (e:Exception){
                e.printStackTrace()
                Log.d(TAG,"跳转出错" + e.message)
            }
        }
    }

    private fun checkPermissions(): Boolean {
        when {
            Build.VERSION.SDK_INT >= 33 -> {
                val permissions = arrayOf(
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                )
                for (permission in permissions) {
                    return Environment.isExternalStorageManager()
                }
            }

            else -> {
                for (permission in PERMISSIONS) {
                    if (ContextCompat.checkSelfPermission(
                            this,
                            permission
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        return false
                    }
                }
            }
        }
        return true
    }

    private fun requestPermission() {
        when {
            Build.VERSION.SDK_INT >= 33 -> {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.READ_MEDIA_IMAGES,Manifest.permission.READ_MEDIA_AUDIO,Manifest.permission.READ_MEDIA_VIDEO,Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO),
                    REQUEST_PERMISSION_CODE
                )
            }

            else -> {
                ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_CODE)
            }
        }
    }

    private fun performFileOperations() {
        //BaseApplication.Instance.initMMKV()
        // 执行文件读写操作
        initMMKVData()
        initView()
    }

    private fun initMMKVData() {
        // 存储数据
        MMKVUtils.getInstance().encode("key1", "用户小明")
        MMKVUtils.getInstance().encode("age",  23)
        MMKVUtils.getInstance().encode("sex", "男")
        MMKVUtils.getInstance().encode("address", "北京市朝阳区")
        MMKVUtils.getInstance().encode("birthday", "2020-01-18")
        MMKVUtils.getInstance().encode("account", "18888888888")
        MMKVUtils.getInstance().encode("identity", true)
        MMKVUtils.getInstance().encode("amount", 888888.88)
    }

    override fun onResume() {
        super.onResume()
        val backValue = MMKVUtils.getInstance().decodeString("backKey")
        Log.d(TAG, "====从第三方返回的数据为===$backValue")
        tvBackData.text = "返回时数据是:$backValue"
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_PERMISSION_CODE -> {
                var allPermissionsGranted = true
                for (result in grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        allPermissionsGranted = false
                        break
                    }
                }
                when {
                    allPermissionsGranted -> {
                        // 权限已授予，执行文件读写操作
                        performFileOperations()
                    }
                    else -> {
                        // 权限被拒绝，处理权限请求失败的情况
                        requestPermission()
                    }
                }
            }
        }
    }

}